package com.aigestudio.demo.com.aigestudio.tabview;

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.widget.Toast;
import com.aigestudio.demo.R;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.view.WheelTime;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by Fcy on 2016/6/19.实现处理数据的接口，模块化处理
 */
public abstract class BaseTimeTabActivity extends Activity
        implements ITimeTabData, TimeController.ICustomTimeAction {

    protected TimeController mTimeController;
    private String[] mContentArr;
    protected int[] mTimeKeyArr;
    private TabLayout mTabLayout;
    private int mCurrPos;
    private TimePickerView pvTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView();

        // 或者我直接先创建我的布局，然后把你的布局addview进来，这样你的布局里就不用include我的布局了。
        mCurrPos = initSelectPos();
        mTimeKeyArr = initTimeKeyArr();
        mContentArr = initContentArr();

        initPickView();

        mTimeController = TimeController.getInstance(mTimeKeyArr);
        mTimeController.bindEditView((ArrowEditView) findViewById(R.id.left_time_view),
            (ArrowEditView) findViewById(R.id.right_time_view), findViewById(R.id.btn_confirm));
        mTimeController.setCustomTimeAction(this);

        initTabLayout();
        initCustomView();
        //onTabChange(0);
        //  默认选中第几个tab
        mTabLayout.getTabAt(mCurrPos).select();
    }

    private void initPickView(){
        //时间选择器
        pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        //控制时间范围
//        pvTime.setRange(WheelTime.DEFULT_START_YEAR, Calendar.getInstance().get(Calendar.YEAR));
        pvTime.setTime(new Date());
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        //时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date, String tag) {
                // TODO 起始时间不能选择今天以后的时间？如果是，需要修改确定按钮的处理，不要自动关闭
                if ("1".equals(tag)) {
                    pvTime.dismiss();
                    mTimeController.setEndTime(date.getTime());
                    mTimeController.resetTimeUI();
                } else {
                    if (date.getTime() > System.currentTimeMillis()) {
                        Toast.makeText(BaseTimeTabActivity.this, "起始时间不能选择今天以后的时间", Toast.LENGTH_SHORT).show();
                    } else {
                        pvTime.dismiss();
                        mTimeController.setFromTime(date.getTime());
                        mTimeController.resetTimeUI();
                    }
                }
            }
        });
    }

    protected abstract void setContentView();

    /**
     * @return 默认选中位置
     */
    protected int initSelectPos() {
        return 0;
    }

    protected int getSelectPos() {
        return mCurrPos;
    }

    protected String[] initContentArr() {
        return getResources().getStringArray(R.array.tab_arr);
    }

    protected int[] initTimeKeyArr() {
        return new int[] { TODAY, WEEK, MOUTH, CUSTOM };
    }

    protected abstract void initCustomView();

    private void initTabLayout() {
        mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
        // 设置TabLayout模式
        //mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        // 设置从PagerAdapter中获取Tab
        mTabLayout.setTabsFromPagerAdapter(new TabPagerAdapter());

        // 设置Tab的选择监听，在 setupWithViewPager 之后才有效，替换掉TabLayout自己设置的监听事件
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                onTabChange(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });


    }

    /**
     * @param position
     * @callSuper
     */
    protected void onTabChange(int position) {
        // 这些逻辑都放在basetab中处理，只暴露给子类，需要传递一个array，暴露给子类一个onRefresh方法，提供position和时间戳
        mCurrPos = position;
        mTimeController.resetTime(position);
        //changeState(mTimeController.getTimeKeyArr()[position] == CUSTOM);
        // 如果不是自定义发起请求，否则点击确定发起请求
        if (mTimeController.getTimeKeyArr()[position] != CUSTOM) {
            loadData();
        }
    }

    @Override
    public void clickCustomTime(int position) {
        pvTime.setTime(new Date(mTimeController.getDate(position == 0)));
//        pvTime.show();
        pvTime.show(String.valueOf(position));
    }

    @Override
    public void ConfirmCustomTime() {
        // TODO 确定时间，需要check，前面的时间不能比后面的时间大
        if (mTimeController.checkTime()){
            mTimeController.changeState(false);
            loadData();
        } else {
            Toast.makeText(this,"起始时间不能晚于结束时间",Toast.LENGTH_SHORT).show();
        }
    }

    private void loadData() {
        loadData(mTimeController.getFromTime(), mTimeController.getEndTime());
    }

    /**
     * 加载数据
     *
     * @param fromTime
     * @param endTime
     */
    protected abstract void loadData(long fromTime, long endTime);

    private class TabPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mTimeKeyArr.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return false;
        }

        /**
         * 重写这个方法为tablayout设置title使用
         * {@link android.support.design.widget.TabLayout#setTabsFromPagerAdapter}
         *
         * @param position
         * @return
         */
        @Override
        public CharSequence getPageTitle(int position) {
            return mContentArr[position];
        }
    }
}
